package main

import (
	"flag"
	"github.com/fatih/color"
	"github.com/ifnk/micro-blog/internal/pkg/config"
	"github.com/ifnk/micro-blog/internal/pkg/dbcontext"
	"github.com/ifnk/micro-blog/internal/pkg/log"
	"github.com/ifnk/micro-blog/internal/post"
	"github.com/ifnk/micro-blog/protobuf/post_pb"
	"github.com/pkg/errors"
	"google.golang.org/grpc"
	"google.golang.org/grpc/reflection"
	"net"
)

// 命令行可以 传 config.yaml 的路径 , 默认 的值的是  ./configs/config.yaml
var flagConfig = flag.String("config", "./configs/config.yaml", "path to config file")

func main() {
	flag.Parse()

	logger := log.New()
	// 加载 配置文件 config.yaml 获取 config 实体
	conf, err := config.Load(*flagConfig)
	color.Blue("conf 读取为 conf.Post -> %+v", conf.Post)
	if err != nil {
		logger.Fatal(err)
	}
	logger.Infof("加载的配置文件为 -> %+v", conf)

	// 初始化数据库
	gormDB, jinZhuDB := InitDB(logger, conf)

	//_, jinzhuDB, err := dbcontext.NewPermissionDB(conf)

	if err != nil {
		logger.Fatal(err)
	}

	grpcServer := grpc.NewServer()

	post_pb.RegisterPostServiceServer(grpcServer, InitPostServer(logger, gormDB, jinZhuDB))
	reflection.Register(grpcServer)

	// 监听 user 服务 grpc 端口 50052
	lis, err := net.Listen("tcp", conf.Post.Server.GRPC.Port)
	logger.Infof("监听 post 服务 grpc 端口 嘟嘟    %s", conf.Post.Server.GRPC.Port)
	if err != nil {
		logger.Errorf(" 监听 post 服务 grpc 端口 %+v  失败  failed to listen: %+v", conf.Post.Server.GRPC.Port, err)
	}

	if err = grpcServer.Serve(lis); err != nil {
		logger.Errorf("post 服务 grpc 启动失败!  failed to serve: %v", err)
	}

}

func InitPostServer(logger *log.Logger, gormDB *dbcontext.GormDB, jinzhuDB *dbcontext.JinZhuDB) *post.Server {
	server := post.NewPostServer(logger, gormDB, jinzhuDB)
	return &server
}
func InitDB(logger *log.Logger, conf *config.Config) (*dbcontext.GormDB, *dbcontext.JinZhuDB) {
	gormDB, jinzhuDB, err := dbcontext.NewPostDB(conf)
	if err != nil {
		logger.Fatal("数据库  post   连接失败! err -> %+v", err)
	}
	// 自动 迁移 表
	err = gormDB.AutoMigrate(
		&post_pb.PostORM{},
	)
	if err != nil {
		logger.Fatal("数据表  全部  迁移失败! err -> %+v", err)
	}

	// 初始化 post  数据
	InitPostData(gormDB, logger)
	return gormDB, jinzhuDB
}
func InitPostData(db *dbcontext.GormDB, logger *log.Logger) {
	var count int64
	db.Model(&post_pb.PostORM{}).Count(&count)
	if count == 0 {
		//  表为空的话 创建种子数据
		logger.Infof("post 表数据为空,将创建种子数据")
		entities := []post_pb.PostORM{
			{Id: 1, Content: "性别", Title: "嘟嘟标题1", CommentCount: 1, UserId: 1},
			{Id: 2, Content: "数据库int类型", Title: "嘟嘟标题2", CommentCount: 0, UserId: 1},
			{Id: 3, Content: "数据库时间日期类型", Title: "嘟嘟标题3", CommentCount: 0, UserId: 1},
			{Id: 4, Content: "数据库浮点型", Title: "嘟嘟标题4", CommentCount: 0, UserId: 1},
			{Id: 5, Content: "数据库字符串", Title: "嘟嘟标题5", CommentCount: 0, UserId: 1},
			{Id: 6, Content: "数据库bool类型", Title: "嘟嘟标题6", CommentCount: 0, UserId: 1},
		}
		err := db.Create(&entities).Error
		if err != nil {
			err = errors.Wrap(err, "users  表数据初始化失败!")
			logger.Fatal(err)
		}
	}
}
